package com.toppitch.site.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.toppitch.site.data.HedgeFund;
import com.toppitch.site.data.JsonData;
import com.toppitch.site.data.Student;
import com.toppitch.site.db.DBManager;

@Controller
public class LoginController extends BaseController {
	@Autowired
	private DBManager dbmanager;

	@RequestMapping(value = "/studentLogin", method = RequestMethod.POST)
	public String login(@RequestParam("email") String email,
			@RequestParam("password") String password, HttpSession session,
			ModelMap modelMap) {
		cleanSession(session);
		Student student = new Student();
		dbmanager.queryFirst(student,
				"select * from student where lower(email)=? and password=?", email.toLowerCase(),
				password);

		JsonData jd = new JsonData();
		modelMap.addAttribute("jsonData", jd);
		if (email.equalsIgnoreCase(student.getEmail())) {
			jd.setSucceed(true);
			session.setAttribute("STUDENT", student);
		} else {
			jd.setSucceed(false);
			jd.setErrorMessage("Incorrect password entered. Please try again.");
		}

		return "json";
	}

	@RequestMapping(value = "/hfLogin", method = RequestMethod.POST)
	public String hfLogin(@RequestParam("email") String email,
			@RequestParam("password") String password, HttpSession session,
			ModelMap modelMap) {
		cleanSession(session);
		HedgeFund hf = new HedgeFund();
		dbmanager.queryFirst(hf,
				"select * from hf where lower(email)=? and password=?", email.toLowerCase(),
				password);

		JsonData jd = new JsonData();
		modelMap.addAttribute("jsonData", jd);
		if (email.equalsIgnoreCase(hf.getEmail())) {
			jd.setSucceed(true);
			session.setAttribute("HF", hf);
		} else {
			jd.setSucceed(false);
			jd.setErrorMessage("Incorrect password entered. Please try again.");
		}

		return "json";
	}

	private void cleanSession(HttpSession session) {
		session.removeAttribute("STUDENT");
		session.removeAttribute("HF");
	}
}
